<template>
    <div>
        <div class="box">
            <horder class="horder">
                <van-nav-bar title="标题" left-text="返回" left-arrow @click-left="$router.go(-1)" />
            </horder>
            <main class="main">
                <van-form @submit="onSubmit">
                    <van-cell-group inset>
                        <van-field v-model="username" name="username" label="用户名" placeholder="用户名" :rules="[{ required: true, message: '请填写用户名' }, { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
                        ]" />
                        <van-field v-model="password" type="password" name="password" label="密码" placeholder="密码"
                            :rules="[{ required: true, message: '请填写密码' },{ pattern: /^\d{6}$/, message: '请输入6位数字' }]" />
                    </van-cell-group>
                    

                    <van-cell-group inset>
                        <van-field v-model="sms" center clearable label="短信验证码" placeholder="请输入短信验证码" :rules="[{ required: true, message: '请填写短信验证码' }]">
                            <template #button>
                                <van-button size="small" type="primary" @click="dj" :disabled="msg!='获取验证码' || username.length !=11">{{msg}}</van-button>
                            </template>
                        </van-field>
                    </van-cell-group>
                    <div style="margin: 16px;">
                        <van-button round block type="primary" native-type="submit">
                            登录
                        </van-button>
                    </div>
                </van-form>
                <p style="text-align: right;padding-right: 20px;" @click="$router.push('/zc')">快速注册</p>
            </main>

        </div>
    </div>
</template>

<script setup>
import { ref } from 'vue';
import api from '@/api/api'
import { showSuccessToast, showFailToast } from 'vant';
import { useRouter, } from 'vue-router'
const router = useRouter()

const msg=ref('获取验证码')
const sms=ref('')

const username = ref('');
const password = ref('');

const timer=ref(null)
const count=ref(60)

const onSubmit = (values) => {
    console.log('submit', values);
    api.post('/login', values).then(res => {
        if (res.data.code == 200) {
            showSuccessToast('登录成功')
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('username', username.value)
            router.push('/')
        } else {
            showFailToast('登录失败');
        }
    })
};

const dj=()=>{
    msg.value=count.value+'获取验证码'
    api.get('/code').then(res=>{
        if(res.data.code==200){
            sms.value=res.data.data
        }
    })
 timer.value=setInterval(()=>{
count.value--
if(count.value==0){
    clearInterval(timer.value)
    msg.value='获取验证码'
    count.value=60
}else{
    msg.value=count.value+'秒后重新获取'
}
 },1000)
}


</script>

<style lang="scss" scoped></style>